// src/stores/document.ts
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { documentApi } from '@/api/document'
import type { DocumentTask, TaskCreateRequest } from '@/types/document'

export const useDocumentStore = defineStore('document', () => {
  const currentTask = ref<DocumentTask | null>(null)
  const taskList = ref<DocumentTask[]>([])
  const loading = ref(false)
  const resultHtml = ref<string>('')

  const createTask = async (request: TaskCreateRequest) => {
    loading.value = true
    try {
      console.log('创建任务请求:', request)
      const task = await documentApi.createTask(request)
      console.log('创建任务响应:', task)
      console.log('任务ID:', task.data.taskId) // 确保这个有值
      currentTask.value = task.data
      return task.data
    } finally {
      loading.value = false
    }
  }

  // 在 fetchTask 方法中添加日志
  const fetchTask = async (taskId: string) => {
    loading.value = true
    try {
      console.log('获取任务详情, taskId:', taskId)
      const task = await documentApi.getTask(taskId)
      console.log('获取任务详情响应:', task)
      currentTask.value = task.data
      return task.data
    } finally {
      loading.value = false
    }
  }

  // 获取任务结果
  const fetchTaskResult = async (taskId: string) => {
    try {
      const html = await documentApi.getTaskResult(taskId)
      resultHtml.value = html
      return html
    } catch (error) {
      resultHtml.value = '<p>获取文档结果失败</p>'
      throw error
    }
  }

  // 导出文档
  const exportDocument = async (taskId: string, format: 'html' | 'md') => {
    await documentApi.exportDocument(taskId, format)
  }

  // 获取任务列表
  const fetchTaskList = async (params?: { page?: number; size?: number }) => {
    loading.value = true
    try {
      const response = await documentApi.getTaskList(params)
      taskList.value = response.records
      return response
    } finally {
      loading.value = false
    }
  }

  // 删除任务
  const deleteTask = async (taskId: string) => {
    await documentApi.deleteTask(taskId)
    // 从列表中移除
    const index = taskList.value.findIndex((task) => task.taskId === taskId)
    if (index > -1) {
      taskList.value.splice(index, 1)
    }
    // 如果删除的是当前任务，清空当前任务
    if (currentTask.value?.taskId === taskId) {
      currentTask.value = null
      resultHtml.value = ''
    }
  }

  // 清空状态
  const clearState = () => {
    currentTask.value = null
    resultHtml.value = ''
  }

  return {
    // state
    currentTask,
    taskList,
    loading,
    resultHtml,

    // actions
    createTask,
    fetchTask,
    fetchTaskResult,
    exportDocument,
    fetchTaskList,
    deleteTask,
    clearState,
  }
})
